<?php

declare(strict_types=1);

namespace App\Request\Admin;

use App\Constants\Admin\AdminCode;
use App\Request\FormRequest;
use Hyperf\Validation\Rule;

/**
 * 管理员场景验证
 * @author zx
 * @package App\Request\Admin
 */
class Admin extends FormRequest
{
    /**
     * 验证场景
     * @var array|\string[][]
     */
    protected array $scenes = [
        'save' => [
            'head_img',
            'nickname',
            'username',
            'password',
            'mobile',
            'email',
            'is_admin',
            'status',
            'role',
            'role.*'
        ],
        'update' => [
            'head_img',
            'nickname',
            'password',
            'mobile',
            'email',
            'is_admin',
            'status',
            'role',
            'role.*'
        ],
        'destroy' => [
            'ids',
            'ids.*'
        ]
    ];

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $rules = [
            'head_img' => 'url',
            'nickname' => [
                'required',
                'max:15',
                Rule::unique('admin')->ignore($this->route('id'))
            ],
            'username' => [
                'required',
                'between:5,18',
                'alpha_dash',
                Rule::unique('admin')->ignore($this->route('id'))
            ],
            'password' => 'required|between:6,32',
            'mobile' => 'mobile',
            'email' => 'email',
            'is_admin' => 'in:0,1',
            'status' => 'in:'.implode(',', AdminCode::$statusMap),
            'role' => 'required_unless:is_admin,1|array',
            'role.*' => 'required_unless:is_admin,1|numeric|min:1'
        ];

        switch (strtolower($this->getMethod())) {
            case 'put':
                $rules['password'] = 'between:6,32';
                unset($rules['username']);
                break;
            case 'delete':
                $rules = [
                    'ids' => 'required|array',
                    'ids.*' => 'required|numeric|min:1'
                ];
                break;
        }

        return $rules;
    }
}
